package com.ruoyi.smart.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.smart.service.DeviceControlService;
import com.ruoyi.smart.service.DeviceStatusService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 设备控制接口
 */
@RestController
@RequestMapping("/smart/device/control")
public class DeviceController extends BaseController {

    private final DeviceControlService deviceControlService;
    private final DeviceStatusService deviceStatusService;

    public DeviceController(DeviceControlService deviceControlService,
                            DeviceStatusService deviceStatusService) {
        this.deviceControlService = deviceControlService;
        this.deviceStatusService = deviceStatusService;
    }

    /**
     * 发送控制命令到设备
     */
    @PostMapping("/command/{deviceId}")
    public AjaxResult sendCommand(@PathVariable String deviceId, @RequestBody String command) {
        deviceControlService.sendControlCommand(deviceId, command);
        return AjaxResult.success("命令已发送");
    }

    /**
     * 批量控制设备
     */
    @PostMapping("/batchCommand")
    public AjaxResult batchSendCommand(@RequestBody Map<String, String> deviceCommands) {
        deviceControlService.batchSendControlCommand(deviceCommands);
        return AjaxResult.success("批量命令已发送");
    }

    /**
     * 按设备类型批量控制
     */
    @PostMapping("/batchByType/{deviceType}")
    public AjaxResult batchSendByType(@PathVariable String deviceType, @RequestBody String command) {
        deviceControlService.batchSendCommandByType(deviceType, command, deviceStatusService);
        return AjaxResult.success("类型批量命令已发送");
    }

    /**
     * 按设备状态批量控制
     */
    @PostMapping("/batchByStatus/{online}")
    public AjaxResult batchSendByStatus(@PathVariable Boolean online, @RequestBody String command) {
        deviceControlService.batchSendCommandByStatus(online, command, deviceStatusService);
        return AjaxResult.success("状态批量命令已发送");
    }

    /**
     * 获取设备控制历史
     */
    @GetMapping("/history/{deviceId}")
    public AjaxResult getControlHistory(@PathVariable String deviceId,
                                        @RequestParam(defaultValue = "10") int limit) {
        return AjaxResult.success(deviceControlService.getControlHistory(deviceId, limit));
    }
}
